import paho.mqtt.client as mqtt
import base64
import time

# MQTT服务器配置
MQTT_BROKER = "139.9.41.7"  
MQTT_PORT = 1883  
MQTT_TOPIC = "MCU/channel-1/order/photo"  
MQTT_USERNAME = "ESP32_S3_sever" 
MQTT_PASSWORD = "b>Vs;>d8yd|atWD};C}>"  

# 回调函数：当客户端成功连接到MQTT服务器时
def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    client.subscribe(MQTT_TOPIC)  # 订阅主题

# 回调函数：当客户端接收到MQTT服务器的消息时
def on_message(client, userdata, msg):
    print(f"Received message on topic {msg.topic}: {len(msg.payload)} bytes")
    # 将接收到的消息保存为图片文件
    with open("received_image.jpg", "wb") as img_file:
        img_file.write(base64.b64decode(msg.payload))
    print("Image saved as received_image.jpg")

# 回调函数：当客户端断开连接时
def on_disconnect(client, userdata, rc):
    print(f"Disconnected with result code {rc}")

# 创建MQTT客户端
client = mqtt.Client()

# 设置回调函数
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect

# 设置用户名和密码
client.username_pw_set(MQTT_USERNAME, password=MQTT_PASSWORD)

# 连接到MQTT服务器
client.connect(MQTT_BROKER, MQTT_PORT, 60)

# 启动网络循环，保持与MQTT服务器的连接
client.loop_start()

# 等待一段时间，让客户端有时间连接和接收消息
time.sleep(5)

# 发送图片
def send_image(client, image_path):
    with open(image_path, "rb") as img_file:
        img_data = img_file.read()
    img_encoded = base64.b64encode(img_data).decode('utf-8')
    client.publish(MQTT_TOPIC, img_encoded)
    print(f"Sent image from {image_path}")

# 替换为你的图片路径
IMAGE_PATH = r"test_order/step1.jpg"
send_image(client, IMAGE_PATH)

# 等待一段时间，让客户端有时间发送消息
time.sleep(10)

# 停止网络循环并断开连接
client.loop_stop()
client.disconnect()